# 异常处理
# 语法
# try:
#   代码块
# except [异常类 [as 异常变量名]]: 
#   异常处理
# except [异常类 [as 异常变量名]]: 
#   异常处理
# ....
# ....
# else:
#   代码块(没出错时执行的代码)
# finally:
#   代码块(出不出错都会执行)
# 抛出异常：
#   raise 异常类或者异常对象

try:
    print(1/0)
except : # 当except后面不跟任何异常对象时，会捕获所有异常
    pass

try:
    print(aa)
except NameError: # 捕获NameError异常
    # raise # 抛出异常
    pass
except ZeroDivisionError: # 捕获除0异常
    pass
except Exception: # 所有异常类的父类
    print('unknow error')

try:
    print(10/1)
except Exception as e: # 获取异常对象，将异常赋值给e
    # raise e
    print('error ->', e)
else:
    print('execute ok')
finally:
    pass


def fn1(a,b):
    if a + b < 0:
        raise Exception # 抛出异常类，没有错误信息
    if a + b == 0:
        raise Exception('this is error msg') # 抛出异常对象, 带有异常信息
    return a + b
try:
    fn1(1,-1)
except Exception as e:
    print('fn1 ->', e)

# 自定义异常
class MyError(Exception):
    pass

def fn2(a,b):
    if a == 0 or b == 0:
        raise MyError('both a and b can\'t be zero')
    return a ** b

print(fn2(0,3))
